import { Component, OnInit, Host } from '@angular/core';
import { Store } from '@ngrx/store';

import { MapState, markersSelector } from '../../store';
import { Marker } from '../../models';

import Ol_Layer_Vector from 'ol/layer/vector';
import Ol_Source_Vector from 'ol/source/vector';
import Ol_Style from 'ol/style/style';
import Ol_Style_Icon from 'ol/style/icon';
import Ol_Feature from 'ol/feature';
import Ol_Geom_Point from 'ol/geom/point';

import { MapComponent } from '../../../ngx-ol/components/map/map.component';

@Component({
  selector: 'ege-map-marker',
  templateUrl: './map-marker.component.html',
  styleUrls: ['./map-marker.component.scss']
})
export class MapMarkerComponent implements OnInit {

  markerLayer: any;
  markerSource: any;


  constructor(
    private store: Store<MapState>,
    @Host() protected host: MapComponent
  ) { }

  ngOnInit() {
    this.initMarkerLayer();
    this.store.select(markersSelector.getLastAdd)
      .subscribe((marker: Marker) => {
        if(marker) {
          this.addMarker(marker);
        }
      });
    this.store.select(markersSelector.getClearMarkers)
      .subscribe((clear: boolean) => {
        if(clear === true) {
          this.clearMarkers();
        }
      })
  }

  initMarkerLayer(): void {
    this.markerSource = new Ol_Source_Vector();
    this.markerLayer = new Ol_Layer_Vector({
      source: this.markerSource,
      style: (feature) => {
        return this.markerStyle();
      },
      zIndex: 10000
    });
    this.host.instance.addLayer(this.markerLayer);
  }

  markerStyle(): any {
    let image = new Image(44, 64);
    image.src = '/assets/images/map-marker.png';
    return new Ol_Style({
      image: new Ol_Style_Icon({
        img: image,
        imgSize: [44, 64],
        scale: 0.568
      })
    });
  }

  addMarker(marker: Marker): void {
    const feature = new Ol_Feature({
      geometry: new Ol_Geom_Point(marker.point),
      name: marker.title
    });
    this.markerSource.addFeature(feature);
  }

  clearMarkers(): void {
    this.markerSource && this.markerSource.clear();
  }



}
